package info.nixbear.tgcms.admin.client.view;

import info.nixbear.tgcms.admin.client.activity.PagesActivity;
import info.nixbear.tgcms.admin.client.place.PagesPlace.PageEditPlace;
import info.nixbear.tgcms.admin.shared.request.PageProxy;

import java.util.List;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.Range;
import com.google.gwt.view.client.RowCountChangeEvent;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;

public class PagesView extends Composite {
	
	PagesActivity presenter;
	
	public void setPagesActivity(PagesActivity pagesActivity) {
		this.presenter = pagesActivity;
	}
	
	
	interface PagesViewUiBinder extends UiBinder<Widget, PagesView> { }
	
	private static PagesViewUiBinder uiBinder = GWT.create(PagesViewUiBinder.class);

	ProvidesKey<PageProxy> keyProvider = new ProvidesKey<PageProxy>() {
		public Object getKey(PageProxy item) {
			return (item == null) ? null : item.stableId();
		}
	};

	@UiField(provided = true)
	final CellList<PageProxy> cellList = new CellList<PageProxy>(new PageCell(), keyProvider);//


	public PagesView() {
		initWidget(uiBinder.createAndBindUi(this));

		// Add a selection model using the same keyProvider.
		final SingleSelectionModel<PageProxy> selectionModel = 
			new SingleSelectionModel<PageProxy>(keyProvider);
		
		cellList.setSelectionModel(selectionModel);
		
		selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
			public void onSelectionChange(SelectionChangeEvent event) {
				PageProxy selected = selectionModel.getSelectedObject();
				if (selected != null) {
					presenter.goTo(new PageEditPlace(Long.toString(selected.getId()), selected));
					selectionModel.setSelected(selected, false);
				}
			}
		});
		
		cellList.addRowCountChangeHandler(new RowCountChangeEvent.Handler() {
	        @Override
	        public void onRowCountChange(RowCountChangeEvent event) {
	        	cellList.setVisibleRange(new Range(0, event.getNewRowCount()));
	        }
	    });
	}

	/**
	 * A custom {@link Cell} used to render a {@link Contact}.
	 */
	private static class PageCell extends AbstractCell<PageProxy> {
		@Override
		public void render(Context context, PageProxy page, SafeHtmlBuilder sb) {
			if (page != null) {
				sb.appendEscaped(page.getTitle());
			}
		}
	}
	
	public void setPages(List<PageProxy> pages) {
		cellList.setRowCount(pages.size(), true);
		cellList.setRowData(0, pages);
	}


}
